<template>
    <div>
      <!--面包屑导航-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!--卡片部分-->
      <el-card>
        <!--添加角色按钮-->
        <el-row>
          <el-col>
            <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
          </el-col>
        </el-row>
        <!--角色列表-->
        <el-table :data="rolesList" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['bdbottom', index === 0? 'bdtop':'', 'vcenter']"
                      v-for="(tag,index) in scope.row.children" :key="tag.id">
                <!--渲染一级权限-->
                <el-col :span="5">
                  <el-tag closable type="primary"
                          @close="removeRightById(scope.row,tag.id)">
                    {{tag.authName}}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!--渲染二级和三级权限-->
                <el-col :span="19">
                  <el-row :class="[indx === 0? '':'bdtop', 'vcenter']"
                          v-for="(secTag, indx) in tag.children" :key="secTag.id">
                    <el-col :span="6">
                      <el-tag closable type="success"
                              @close="removeRightById(scope.row,secTag.id)">
                        {{secTag.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag closable type="warning"
                              @close="removeRightById(scope.row,thrdTag.id)"
                              v-for="thrdTag in secTag.children" :key="thrdTag.id">
                        {{thrdTag.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" width="320px">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showReviseDialog(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row.id)">删除</el-button>
              <el-button type="warning" icon="el-icon-setting" size="mini"  @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分配权限对话框-->
        <el-dialog
          title="分配权限"
          :visible.sync="setRightDialogVisible"
          width="50%"
        @close="setRightDialogClosed"
        >
          <!--树形控件-->
          <el-tree
            :data="rightsList" :props="treeProps"
            show-checkbox node-key="id"
            default-expand-all
            :default-checked-keys="defKeys"
            ref="treeRef"
          >
          </el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
          </span>
        </el-dialog>
        <!--添加角色对话框-->
        <el-dialog
          title="添加角色"
          :visible.sync="addRoleDialogVisible"
          width="50%" @close="addRoleFormClosed">
          <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="roleRef" label-width="90px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addRoleForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
    <el-button @click="addRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
        </el-dialog>
        <!--编辑角色对话框-->
        <el-dialog
          title="编辑角色"
          :visible.sync="reviseRoleDialogVisible"
          width="50%" @close="reviseRoleFormClosed">
          <el-form :model="reviseRoleForm" :rules="addRoleFormRules" ref="reviseRoleRef" label-width="90px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="reviseRoleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="reviseRoleForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
    <el-button @click="reviseRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="reviseRole">确 定</el-button>
  </span>
        </el-dialog>
      </el-card>
    </div>
</template>

<script>
export default {
  created () {
    this.getRolesList()
  },
  data () {
    return {
      rolesList: [],
      setRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleId: '',
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 2, max: 8, message: '长度为2-8个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 4, max: 8, message: '长度为4-8个字符', trigger: 'blur' }
        ]
      },
      addRoleDialogVisible: false,
      reviseRoleDialogVisible: false,
      reviseRoleForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      }
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      console.log(res.data)
    },
    async removeRightById (role, rightid) {
      console.log(role)
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '删除用户权限', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rightid)
        if (res.meta.status !== 200) return this.$message.error('删除权限失败')
        this.$message.success('已成功删除该权限')
        role.children = res.data
      }
      if (confirmResult === 'cancel') return this.$message.info('已取消删除操作')
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rightsList = res.data
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClosed () {
      this.defKeys = []
    },
    async allotRights () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    showAddRoleDialog () {
      this.addRoleDialogVisible = true
    },
    addRole () {
      this.$refs.roleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.getRolesList()
        this.addRoleDialogVisible = false
      })
    },
    addRoleFormClosed () {
      this.$refs.roleRef.resetFields()
    },
    reviseRoleFormClosed () {
      this.$refs.reviseRoleRef.resetFields()
    },
    async showReviseDialog(role) {
      const { data: res } = await this.$http.get(`roles/${role.id}`)
      if (res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.reviseRoleForm = res.data
      this.reviseRoleDialogVisible = true
    },
    reviseRole () {
      this.$refs.reviseRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.reviseRoleForm.roleId, this.reviseRoleForm)
        if (res.meta.status !== 200) return this.$message.error('修改角色失败')
        this.$message.success('角色修改成功')
        this.getRolesList()
        this.reviseRoleDialogVisible = false
      })
    },
    async removeRole (id) {
      const confirmResult = await this.$confirm('您确定要永久删除该角色吗？', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除用户')
        this.$message.success('删除成功')
        this.getRolesList()
      }
      if (confirmResult === 'cancel') return this.$message.info('已取消删除操作')
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
